package com.spzx.user.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.user.domain.Region;
import com.spzx.user.domain.UserAddress;
import com.spzx.user.service.IRegionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.spzx.user.mapper.UserAddressMapper;
import com.spzx.user.service.IUserAddressService;

/**
 * 用户地址Service业务层处理
 *
 * @author atguigu
 * @date 2024-07-10
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService
{
    @Resource
    private UserAddressMapper userAddressMapper;
    @Resource
    private IRegionService regionService;

    @Override
    public int saveUserAddress(UserAddress userAddress) {

        userAddress.setUserId(SecurityUtils.getUserId());
        //查询省市区的标题拼接字符串  ，再拼接完整收货地址
        //使用省市区code分别查询各自的标题
        String provinceName = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, userAddress.getProvinceCode())
                .select(Region::getName)).getName();
        String cityName = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, userAddress.getCityCode())
                .select(Region::getName)).getName();
        String districtName = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, userAddress.getDistrictCode())
                .select(Region::getName)).getName();

        String fullAddress = provinceName+" "+ cityName+" "+districtName+" "+userAddress.getAddress();
        userAddress.setFullAddress(fullAddress);
        //如果本次新增的是默认地址，需要先将之前的默认地址改为非默认的
        if(userAddress.getIsDefault().longValue() == 1l){
            //本次新增默认地址: 修改当前用户的之前所以的默认地址
            this.update(Wrappers.lambdaUpdate(UserAddress.class)
                    .eq(UserAddress::getUserId , SecurityUtils.getUserId())
                    .eq(UserAddress::getIsDefault , 1)
                    .set(UserAddress::getIsDefault , 0));
        }

        return baseMapper.insert(userAddress);
    }
}
